const Router = require('koa-router')
const router = new Router()
const { koaBody } = require('koa-body')
const { isEmpty, isEmail } = require('../utils/verify')
const Message = require('../models/Message')

router.prefix('/message')
router.post('/create', async (ctx) => {
  const { content, name, title, email } = ctx.request.body
  if (isEmpty(String(content))) {
    return (ctx.body = {
      code: 422,
      data: { message: '内容不能是空的' },
    })
  }
  if (isEmpty(String(name))) {
    return (ctx.body = {
      code: 422,
      data: { message: '名字不能是空的' },
    })
  }
  if (isEmpty(String(title))) {
    return (ctx.body = {
      code: 422,
      data: { message: '主题题不能是空的' },
    })
  }
  if (isEmpty(String(email))) {
    return (ctx.body = {
      code: 422,
      data: { message: '邮箱不能是空的' },
    })
  }
  if (!isEmail(email)) {
    return (ctx.body = {
      code: 422,
      data: { message: '邮箱格式不正确' },
    })
  }
  try {
    const result = await Message.create({
      content,
      name,
      title,
      email,
    })
    if (!result) {
      throw new Error('留言创建失败')
    }
    ctx.body = {
      code: 200,
      data: true,
    }
  } catch (e) {
    throw new Error(`留言创建失败,${e.message}`)
  }
})

module.exports = router
